<?php
include('../includes/classes/core.php');

$action	= $_REQUEST['act'];
$user_id	= $_SESSION['USERID'];
$error	= '';
$data	= '';

switch ($action) {
	case 'get_workers':
		$status	= $_REQUEST['status'];
		$page 		= GetPage($status);
		$data[page]	= $page;
		if($status==1 or $status==5){
		    $type=$type.'
						<select id="worc_type"  class="idls">';
		    $r = 	mysql_query("SELECT `id`,`name` FROM `work_type`" );
		    while ( $res = mysql_fetch_row($r)){
		        $type=$type."<option  value='$res[0]'>$res[1]</option>";
		    };
		    $type=$type.'> </select>';
		$data[page1]	= $type;
		}

		break;
	case 'log-in':
		$user		= $_REQUEST['user'];

		$password	= $_REQUEST['password'];
		$action     = $_REQUEST['action'];

		$answ		= check($user,$password, $action);
		$data		= array('answ'	=> $answ);

		break;
	case 'all_work_end' :
	mysql_query("UPDATE worker_action
				SET
				end_date = NOW(),
				actived  = 0
                WHERE   actived=1");
	    $data	= array('message'	=> "გთხოვთ თავიდან გაიაროთ ავტორიზაცია");	
	    break;		
		
	case 'get_part_list' :
		$page 		= GetPartPage();
		$data		= array('page'	=> $page);

		break;
	case 'get_worker_list' :
		$page 		= GetWorkerPage();
		$data		= array('page'	=> $page);

		break;
	case 'get_info_list' :
		$barcode	= $_REQUEST['barcode'];
		if($barcode != ""){
			$page 		= GetInfoPage($barcode);
		}else{
			$page 		= GetStaticInfoPage();
		}
		$data		= array('page'	=> $page);

		break;
	case 'get_history_list' :
		$barcode	= $_REQUEST['barcode'];
		if($barcode != ""){
			$page 		= GetHistoryPage($barcode);
		}else{
			$page 		= '';
		}
		$data		= array('page'	=> $page);
		break;
	case 'save_part' :
		$cartridgeID = $_REQUEST['cartridgeID'];
		$part		 = json_decode( '['.$_REQUEST['list'].']' );
		$barcode	 = $_REQUEST['barcode'];
		$person		 = $_REQUEST['person'];
		$wareHouseID = $_REQUEST['wareHouseID'];

		if($barcode != '' && strlen($barcode) == '15'){
			SavePart($wareHouseID,$person,$part,$cartridgeID,$barcode);
		}else{
			$error = 'შტრიხკოდი არასწორია';
		}
		break;
    default:
       $error = 'Action is Null';
}

$data['error'] = $error;

echo json_encode($data);


function GetWorkersByStatus($status){
	$data = '';
	switch ($status){
		case '1' :
			$req = mysql_query("SELECT	    DISTINCT `persons`.`id`,
										    `persons`.`name`
								FROM		`persons`
								LEFT JOIN	`worker_action` ON `worker_action`.`person_id` = `persons`.`id`
								WHERE      ISNULL(worker_action.actived) OR (SELECT actived FROM worker_action WHERE person_id = `persons`.`id` ORDER BY id DESC LIMIT 1) = 0
								");
			break;
		case '4' :
		    $req = mysql_query("SELECT     DISTINCT `persons`.`id`,
									  `persons`.`name`
							FROM	  `persons`
							LEFT JOIN `worker_action` ON `worker_action`.`person_id` = `persons`.`id`
							WHERE      worker_action.actived = 2
							");

		    break;

	    case '3' :

	        $req = mysql_query("SELECT	     DISTINCT `persons`.`id`,
									    `persons`.`name`
							FROM		`persons`
							LEFT JOIN	`worker_action` ON `worker_action`.`person_id` = `persons`.`id`
						    WHERE       (`persons`.`actived` = 1 AND `persons`.`position`= 13) AND (worker_action.actived = 1)
							");

	        break;
		case '2' or '5' :

			$req = mysql_query("SELECT	    DISTINCT `persons`.`id`,
										    `persons`.`name`
								FROM		`persons`
								LEFT JOIN	`worker_action` ON `worker_action`.`person_id` = `persons`.`id`
								WHERE `worker_action`.`actived` = 1 && `persons`.`actived` = 1 && `persons`.`position`= 13
							    -- WHERE      (`persons`.`actived` = 1 AND `persons`.`position`= 13) AND (worker_action.actived = 1 OR worker_action.actived = 3)
								");

			break;
		default:
			$req = mysql_query("SELECT	     DISTINCT `persons`.`id`,
										    `persons`.`name`
								FROM		`persons`
								LEFT JOIN	`worker_action` ON `worker_action`.`person_id` = `persons`.`id`
					            WHERE       `persons`.`actived` = 1 AND `persons`.`position`= 13
								");

			break;
	}


	$data .= '<option>-აირჩიეთ მომხმარებელი-</option>';


	while( $res = mysql_fetch_assoc($req)){
		$data .= '<option value="' . $res['id'] . '">' . $res['name'] . '</option>';
	}

	$data .= '</div>';

	return $data;
}

function GetPage($status){

	$data .= '<select id="user" class="idls">'.GetWorkersByStatus($status).'</select>';

	return $data;
}

function check($user,$password, $action){
	$rResult = mysql_query("SELECT	`id`
							FROM	`persons`
							WHERE	`id` = '$user' && `password` = '$password'");
	$aRow = mysql_fetch_array( $rResult );
	if($aRow != ''){

		switch ($action){
			case '1' :
				WorkerStart($user);
				break;
			case '2' :
				WorkerEnd($user);
				break;
			case '3' :
				GoTimeOut($user);
				break;
			case '4' :
				BackTimeOut($user);
				break;
			case '5' :
			    work_change($user);
			    break;
			default:
				break;
		}

		return true;
	}else{
		return false;
	}
}

function WorkerStart($user){
	$worc_type	= $_REQUEST['worc_type'];
	mysql_query("INSERT INTO  worker_action
				     (person_id, start_date, actived)
				 VALUES
				     ($user, NOW(), 1)
			    ");
	$id=mysql_insert_id();
	mysql_query("INSERT INTO   `worker_action_detail`
	                           (`date`, `worker_action_id`,`work_type_id`)
	                     VALUES ( NOW(), $id, $worc_type)");

}


function WorkerEnd($user){

	$date = date('Y-m-d H:i:s');

	$res = mysql_fetch_assoc(mysql_query("SELECT  MAX(id) AS `id`
											FROM  worker_action
											WHERE person_id = $user"));

	mysql_query("UPDATE worker_action
				SET
				end_date = '$date',
				actived  = 0
				WHERE    person_id = $user AND id = $res[id]");
}

function GoTimeOut($user){

	$date = date('Y-m-d H:i:s');

	$res = mysql_fetch_assoc(mysql_query("SELECT  MAX(id) AS `id`
											FROM  worker_action
											WHERE person_id = $user"));

	mysql_query("UPDATE worker_action
				 SET
				 timeout_start_date = '$date',
				 actived            = 2
				 WHERE person_id    = $user AND id = $res[id]");
}

function BackTimeOut($user){
	$date = date('Y-m-d H:i:s');

	$res = mysql_fetch_assoc(mysql_query("SELECT  MAX(id) AS `id`
			FROM  worker_action
			WHERE person_id = $user"));

	mysql_query("UPDATE worker_action
	SET
	timeout_end_date = '$date',
	actived          = 1
	WHERE person_id  = $user AND id = $res[id]");
}
function work_change($user){
    $worc_type	= $_REQUEST['worc_type'];
   $id=mysql_fetch_array(mysql_query("SELECT id FROM `worker_action`;
                                  WHERE actived=1 AND person_id=$user
                                  ORDER BY id DESC LIMIT 1"));

    mysql_query("INSERT INTO   `worker_action_detail`
                (`date`, `worker_action_id`,`work_type_id`)
                VALUES ( NOW(), $id, $worc_type)");

}



function GetPartPage(){
	$data ='';
	$rResult = mysql_query("SELECT		`cartridge_parts_type`.id as `id`,
										`cartridge_parts_type`.`name` as `name`,
										cartridge_parts_type.checked
							FROM		`cartridge_parts_type`
							WHERE		`cartridge_parts_type`.`default` = 1 &&  `cartridge_parts_type`.actived != 0 ");
	while ( $aRow = mysql_fetch_array( $rResult ) )
	{
		$data .= '	<tr class="trClass">
						<td class="tdClass" id="clickID">
								<table width="width: 200px;" >
									<tr>
										<td style="display: none;" id="type">'.$aRow['id'].'
										<td style="width : 20%"><img width="25px" height="25px" src="Administrator-icon.png" /></td>
										<td style="width: 200px;">'.$aRow[1].'</td>
									</tr>
								</table>
						</td>
						<td class="tdClass">';
		if($aRow[2] == '1'){
			$data .= '<input type="checkbox" id="checkbox_'.$aRow['id'].'" class="regular-checkbox" value="'.$aRow['id'].'" checked/><label for="checkbox_'.$aRow[0].'"></label>';
		}else{
			$data .= '<input type="checkbox" id="checkbox_'.$aRow['id'].'" class="regular-checkbox" value="'.$aRow['id'].'" /><label for="checkbox_'.$aRow[0].'"></label>';

		}
		$data .= '				</td>
					</tr>';
	}

	return $data;
}

function GetWorkerPage(){
	$data = '';
	$rResult = mysql_query("SELECT	DISTINCT `persons`.`id`,
									`persons`.`name`,
									`persons`.`image`
							FROM		`persons`
							LEFT JOIN	`worker_action` ON `worker_action`.`person_id` = `persons`.`id`
							WHERE `worker_action`.`actived` = 1 && `persons`.`actived` = 1 && `persons`.`position`= 13");

	while ( $aRow = mysql_fetch_array( $rResult ) )
	{
		if($aRow[2] == ''){
			$aRow[2] ='0.jpg';
		}
		$data .= '
				    <tr>
						<td style="vertical-align: top; " >
					    	<button class="button ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" value="'.$aRow[0].'" id="'.$aRow[0].'">
								<table width="180px" >
									<tr>
										<td style="width : 20%"><img width="25px" height="25px" src="../media/uploads/images/worker/'.$aRow[2].'" /></td>
										<td style="width : 80% ">'.$aRow[1].'</td>
									</tr>
								</table>
							</button>
					    </td>
					</tr>';
	}
	return $data;
}

function GetInfoPage($barcode){
	$rResult1 = mysql_fetch_assoc(mysql_query("SELECT		`warehouse_detail`.`id`
												FROM		`warehouse`
												JOIN 		`warehouse_detail` ON `warehouse_detail`.`warehouse_id` = `warehouse`.`id`
												WHERE 		`warehouse_detail`.`barcode` = '$barcode' AND warehouse_detail.actived=1
												ORDER BY 	`warehouse_detail`.`id` DESC
												LIMIT 1"));

	$rResult = mysql_query("SELECT		`warehouse_detail`.`barcode`,
										`production`.`name`,
										CONCAT(`client`.`name`,'(',`client_objects`.`name`, ')'),
										`warehouse_detail`.`id`,
										`production`.`id`,
										`services_degree`.`comment` AS `comment`
							FROM		`warehouse`
							LEFT JOIN 	( `warehouse_detail` LEFT JOIN `production` ON `production`.`id` = `warehouse_detail`.`prod_id` )ON `warehouse_detail`.`warehouse_id` = `warehouse`.`id`
							LEFT JOIN 	( `client_objects` LEFT JOIN `client` ON `client`.`id` = `client_objects`.`client_id` ) ON `client_objects`.`id` = `warehouse`.`client_object_id`
							LEFT JOIN		`services_degree` ON `services_degree`.`client_object` = `warehouse`.`client_object_id`
							WHERE 		`warehouse_detail`.`barcode` = '$barcode' AND warehouse_detail.actived=1
							ORDER BY 	`services_degree`.`id` DESC, `warehouse`.`start_date` DESC
							LIMIT 1");
	$aRow = mysql_fetch_array( $rResult );
	if($aRow != ''){
		$data ='
		<tr>
			<td  colspan="2">
				<label for="barcode">შტრიხკოდი : </label> '.$aRow[0].'
			</td>
		</tr>
		<tr>
			<td  colspan="2">
				<label for="cartridge">კატრიჯი : </label> '.$aRow[1].'
			</td>
		</tr>
		<tr >
			<td  colspan="2">
				<label for="client_object">კლიენტი : </label> '.$aRow[2].'
			</td>
		</tr>
		<tr>
			<td>
				<label for="client_object">კლიენტის შენიშვნა : </label>
			</td>
			<td>
				<textarea id="comment" style=" background-color: #FFFFFF; border: solid 1px #85b1de; color: black;">' . $aRow['comment'] . '</textarea>
			</td>
		</tr>
		<tr style="display: none;">
			<td colspan="2">
				<input type="hidden" id="warehouseID" value="' .$rResult1[id]. '"/>
			</td>
		</tr>
		<tr style="display: none;">
			<td  colspan="2">
				<input type="hidden" id="cartridgeID" value="' .$aRow[4]. '"/>
			</td>
		</tr>';
		return $data;
	}else{
		global $error;
		$error = 'შტრიხკოდი არასწორია';
		$data  = GetStaticInfoPage();
		return $data;
	}
}
function GetStaticInfoPage(){
	$data ='
		<tr>
			<td  colspan="2">
				<label for="barcode">შტრიხკოდი : </label>
			</td>
		</tr>
		<tr>
			<td  colspan="2">
				<label for="cartridge">კატრიჯი : </label>
			</td>
		</tr>
		<tr>
			<td  colspan="2">
				<label for="client_object">კლიენტი : </label>
			</td>
		</tr>
		<tr>
			<td>
				<label for="client_object">კლიენტის შენიშვნა : </label>
			</td>
			<td>
				<textarea id="comment" style=" background-color: #FFFFFF; border: solid 1px #85b1de; color: black;"></textarea>
			</td>
		</tr>';
	return $data;
}
function GetHistoryPage($barcode){
    $rResult = mysql_query("SELECT     cartridge_parts_type.`name`,
                    					 COUNT(warehouse_producing.cartridge_part_id) AS count,
                                                					 IFNULL(warehouse_producing.count,(
		SELECT count(*)
		FROM  `warehouse_producing`
		JOIN  warehouse_detail 			ON warehouse_detail.id = warehouse_producing.warehouse_detail_id AND warehouse_detail.barcode = '$barcode'
		WHERE      `cartridge_parts_type`.`category` = 2 AND warehouse_producing.cartridge_part_id=2
                            )) as co,
                    					 MAX(DATE(warehouse_producing.date)) as date,
                    			IFNULL(production_category.`cycle`,100) as cycle,
                    			cartridge_parts_type.id
                    FROM      `warehouse_producing`
                    JOIN   warehouse_detail ON warehouse_detail.id = warehouse_producing.warehouse_detail_id AND warehouse_detail.barcode = '$barcode'
                    RIGHT JOIN  cartridge_parts_type ON cartridge_parts_type.id = warehouse_producing.cartridge_part_id
                    LEFT JOIN   cartridge_identity ON cartridge_identity.production_id=SUBSTRING('$barcode',6,4) AND cartridge_identity.parts_type=cartridge_parts_type.id
LEFT JOIN   production_category ON production_category.id = cartridge_identity.parts_category
                    WHERE      `cartridge_parts_type`.`category` = 2
                    GROUP BY  cartridge_parts_type.id");

	while ( $aRow = mysql_fetch_array( $rResult ) )
	{
		$idTd = ($aRow[2] > $aRow[4]) ?  "id='alert_mustchange'" : ""  ;
		$data .= '	<tr ' . $idTd . ' class="trClass">
						<td class="tdClass">'.$aRow[0].'</td>
						<td class="tdClass">'.$aRow[1].'</td>
						<td class="tdClass sss">'.$aRow[2].'</td>
						<td class="tdClass">'.$aRow[3].'</td>
					</tr>';
	}


	return $data;

}

function SavePart($wareHouseID,$person,$part,$cartridgeID,$barcode){
	foreach($part as $partID) {
	    if ($partID==16) {
	        mysql_query("UPDATE   `warehouse_producing_history`
	        LEFT JOIN `warehouse_detail` ON `warehouse_detail`.`id` = `warehouse_producing_history`.`warehouse_detail_id`
	        SET       `warehouse_producing_history`.`count`= 0
	        WHERE    `warehouse_detail`.`barcode` = '$barcode' AND warehouse_producing_history.cartridge_part_id != 2 AND warehouse_producing_history.cartridge_part_id = '$partID' AND warehouse_detail.actived=1");

	        mysql_query("UPDATE   `warehouse_producing`
	        LEFT JOIN `warehouse_detail` ON `warehouse_detail`.`id` = `warehouse_producing`.`warehouse_detail_id`
	        SET       `warehouse_producing`.`count`= 0
	        WHERE    `warehouse_detail`.`barcode` = '$barcode' AND warehouse_producing.cartridge_part_id != 2 AND warehouse_producing.cartridge_part_id = '$partID' AND warehouse_detail.actived=1");
	        InsertPart($person,$wareHouseID,$partID,'0');
	        $res = false;


	    }else {
		$res = true;
		$rResult1 = mysql_query("SELECT		production.id,
        									cartridge_identity.amount
								FROM		cartridge_identity
								LEFT JOIN	production ON production.category = cartridge_identity.parts_category
								WHERE		cartridge_identity.production_id = '$cartridgeID'  AND cartridge_identity.parts_type = '$partID'");
		while ( $aRow1 = mysql_fetch_array( $rResult1 ) )
		{
			$rResult = mysql_query("SELECT		reserve.production_id as `production_id`,
												object.id as `object_id`
									FROM 		reserve
									LEFT JOIN	object ON object.id = reserve.object_id
									WHERE		production_id = '$aRow1[0]' && object.type = 4
									GROUP BY 	production_id
									HAVING 		SUM(quantity - sold)  >= '$aRow1[1]'");

			$rResult = mysql_fetch_array( $rResult );

			if($rResult != '' ){
				mysql_query("UPDATE   `warehouse_producing_history`
							 LEFT JOIN `warehouse_detail` ON `warehouse_detail`.`id` = `warehouse_producing_history`.`warehouse_detail_id`
							 SET       `warehouse_producing_history`.`count`= 0
							 WHERE    `warehouse_detail`.`barcode` = '$barcode' AND warehouse_producing_history.cartridge_part_id != 2 AND warehouse_producing_history.cartridge_part_id = '$partID' AND warehouse_detail.actived=1");

				mysql_query("UPDATE   `warehouse_producing`
							 LEFT JOIN `warehouse_detail` ON `warehouse_detail`.`id` = `warehouse_producing`.`warehouse_detail_id`
							 SET       `warehouse_producing`.`count`= 0
							 WHERE    `warehouse_detail`.`barcode` = '$barcode' AND warehouse_producing.cartridge_part_id != 2 AND warehouse_producing.cartridge_part_id = '$partID' AND warehouse_detail.actived=1");
				InsertPart($person,$wareHouseID,$partID,$rResult[production_id]);
				ReserveTakeOff($rResult['production_id'],$aRow1[1], $rResult['object_id']);
				$res = false;
				break ;
			}
		}
		if( $res == 'true' ){
			global $error;
			$error = "ნაწილი მარაგში ვერ მოიძებნა!";
		}
	}}
	global $error;
	if( $error == "" ){
		$error = "ყველა ოპერაცია წარმატებით განხორციელდა!";
	}

}

function UpdateCount($wareHouseID){
	$rResult1 = mysql_query("	SELECT	`warehouse_detail`.`barcode` as `barcode`
								FROM		`warehouse_detail`
								WHERE		`warehouse_detail`.`id` = '$wareHouseID' AND warehouse_detail.actived=1 ");

	$aRow = mysql_fetch_array($rResult1);


	mysql_query("UPDATE		`warehouse_producing`
				 LEFT JOIN	`warehouse_detail` ON `warehouse_detail`.`id` = `warehouse_producing`.`warehouse_detail_id`
				 SET		`warehouse_producing`.`count`= `warehouse_producing`.`count` + 1
				 WHERE		`warehouse_producing`.`cartridge_part_id` != 2 AND `warehouse_detail`.barcode = '$aRow[barcode]' AND warehouse_detail.actived=1");

	mysql_query("UPDATE		`warehouse_producing_history`
				LEFT JOIN	`warehouse_detail` ON `warehouse_detail`.`id` = `warehouse_producing_history`.`warehouse_detail_id`
				SET			`warehouse_producing_history`.`count`= `warehouse_producing_history`.`count` + 1
				WHERE		`warehouse_producing_history`.`cartridge_part_id` != 2 AND `warehouse_detail`.barcode = '$aRow[barcode]' AND warehouse_detail.actived=1");

}

function InsertPart($person,$wareHouseID,$partID,$productionID){

	if($partID == '2'){
		UpdateCount($wareHouseID);
	}
	$rResult1 = mysql_query("SELECT		`id`
							 FROM		`warehouse_producing`
							 WHERE		`warehouse_producing`.`warehouse_detail_id` = $wareHouseID && `warehouse_producing`.`cartridge_part_id` = $partID
							 ORDER BY	`warehouse_producing`.`id` DESC
							 LIMIT 1 ");

	$aRow = mysql_fetch_array($rResult1);

	if( $aRow == ''){
		$c_data = date('Y-m-d H:i:s');
		mysql_query("INSERT INTO	`warehouse_producing`
						(`person_id`,`warehouse_detail_id`,`cartridge_part_id`,`production_id`,`date`)
					VALUES
						($person,$wareHouseID,$partID,$productionID,'$c_data')");
		mysql_query("INSERT INTO	`warehouse_producing_history`
						(`person_id`,`warehouse_detail_id`,`cartridge_part_id`,`production_id`,`date`)
					VALUES
						($person,$wareHouseID,$partID,$productionID,'$c_data')");

	}else{
		$c_data = date('Y-m-d H:i:s');
		mysql_query("UPDATE		`warehouse_producing`
					 SET		`warehouse_producing`.`date` = '$c_data',
					 			`warehouse_producing`.production_id = $productionID
					 WHERE		`warehouse_producing`.`id` = $aRow[0]");
		mysql_query("UPDATE		`warehouse_producing_history`
					SET			`warehouse_producing_history`.`date` = '$c_data',
								`warehouse_producing_history`.production_id = $productionID
					WHERE		`warehouse_producing_history`.`id` = $aRow[0]");
	}
}

function ReserveTakeOff($prod_id, $quantity, $object)
{
	$req_quantity = $quantity;
	$res = mysql_query("SELECT  `reserve`.`id`,
								`reserve`.`production_id`,
								`reserve`.`object_id`,
								`reserve`.`sold`,
								`reserve`.`quantity` - `reserve`.`sold` AS `diff`,
								`reserve`.`create_date`
						FROM `reserve`
						WHERE `reserve`.`object_id` = $object && `reserve`.`production_id` = $prod_id
						ORDER BY `reserve`.`create_date` ASC" );
	while ($row = mysql_fetch_array($res)) {
		if ($req_quantity != 0) {
			if($row['diff'] > $req_quantity){
				$sum = $row['sold'] + $req_quantity;
				mysql_query("UPDATE `reserve`
				SET	`sold` = $sum
				WHERE	`id` = $row[id]" );
				$req_quantity = 0;
			}else if($row['diff'] == $req_quantity){
				$sum = $row['sold'] + $row['diff'];
				mysql_query("UPDATE `reserve`
				SET	`sold` = $sum
				WHERE	`id` = $row[id]" );
				$req_quantity = 0;
			}else{
				$sum = $row['sold'] + $row['diff'];
				mysql_query("UPDATE `reserve`
				SET	`sold` = $sum
				WHERE	`id` = $row[id]" );
				$req_quantity = $req_quantity - $row['diff'];
			}
		}
	}
}


?>